<!doctype html>




<html class="theme-next pisces" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
    
  
  <link href="//cdn.staticfile.org/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Web,JavaScript," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="高级技巧自定义事件在本书前面，你已经学到事件是JavaScript 与浏览器交互的主要途径。事件是一种叫做观察者的设计模式，这是一种创建松散耦合代码的技术。
对象可以发布事件，用来表示在该对象生命周期中某个有趣的时刻到了。然后其他对象可以观察该对象，等待这些有趣的时刻到来并通过运行代码来响应。
观察者模式由两类对象组成：主体和观察者。主体负责发布事件，同时观察者通过订阅这些事件来观察该主体。该模式">
<meta property="og:type" content="article">
<meta property="og:title" content="《 JavaScript 高级程序设计》备忘-第二十二章-3">
<meta property="og:url" content="http://codingme.xyz/2016/11/08/javascript-note-22-3/index.html">
<meta property="og:site_name" content="CodingMe">
<meta property="og:description" content="高级技巧自定义事件在本书前面，你已经学到事件是JavaScript 与浏览器交互的主要途径。事件是一种叫做观察者的设计模式，这是一种创建松散耦合代码的技术。
对象可以发布事件，用来表示在该对象生命周期中某个有趣的时刻到了。然后其他对象可以观察该对象，等待这些有趣的时刻到来并通过运行代码来响应。
观察者模式由两类对象组成：主体和观察者。主体负责发布事件，同时观察者通过订阅这些事件来观察该主体。该模式">
<meta property="og:updated_time" content="2016-11-09T16:36:29.496Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《 JavaScript 高级程序设计》备忘-第二十二章-3">
<meta name="twitter:description" content="高级技巧自定义事件在本书前面，你已经学到事件是JavaScript 与浏览器交互的主要途径。事件是一种叫做观察者的设计模式，这是一种创建松散耦合代码的技术。
对象可以发布事件，用来表示在该对象生命周期中某个有趣的时刻到了。然后其他对象可以观察该对象，等待这些有趣的时刻到来并通过运行代码来响应。
观察者模式由两类对象组成：主体和观察者。主体负责发布事件，同时观察者通过订阅这些事件来观察该主体。该模式">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post"},
    fancybox: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://codingme.xyz/2016/11/08/javascript-note-22-3/"/>





  <title> 《 JavaScript 高级程序设计》备忘-第二十二章-3 | CodingMe </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">CodingMe</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://codingme.xyz/2016/11/08/javascript-note-22-3/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="Huang SJ">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/uploads/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="CodingMe">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="CodingMe" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                《 JavaScript 高级程序设计》备忘-第二十二章-3
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            

            

            
          </span>

          

          
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="高级技巧"><a href="#高级技巧" class="headerlink" title="高级技巧"></a>高级技巧</h1><h2 id="自定义事件"><a href="#自定义事件" class="headerlink" title="自定义事件"></a>自定义事件</h2><p>在本书前面，你已经学到事件是JavaScript 与浏览器交互的主要途径。<br>事件是一种叫做观察者的设计模式，这是一种创建松散耦合代码的技术。</p>
<p>对象可以发布事件，用来表示在该对象生命周期中某个有趣的时刻到了。<br>然后其他对象可以观察该对象，等待这些有趣的时刻到来并通过运行代码来响应。</p>
<p>观察者模式由两类对象组成：主体和观察者。<br>主体负责发布事件，同时观察者通过订阅这些事件来观察该主体。<br>该模式的一个关键概念是主体并不知道观察者的任何事情，也就是说即使观察者不存在,它也可以独自存在并正常运作。<br>从另一方面来说，观察者知道主体并能注册事件的回调函数（事件处理程序）。<br>涉及DOM 上时，DOM元素便是主体，你的事件处理代码便是观察者。</p>
<p>事件是与DOM 交互的最常见的方式，但它们也可以用于非DOM 代码中——通过实现自定义事件。<br>自定义事件背后的概念是创建一个管理事件的对象，让其他对象监听那些事件。<br><a id="more"></a></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">EventTarget</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">this</span>.handlers = &#123;&#125;;</div><div class="line">&#125;</div><div class="line">EventTarget.prototype = &#123;</div><div class="line">    <span class="keyword">constructor</span>: EventTarget,</div><div class="line">    addHandler: function(type, handler) &#123;</div><div class="line">        <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="keyword">this</span>.handlers[type] == <span class="string">"undefined"</span>) &#123;</div><div class="line">            <span class="keyword">this</span>.handlers[type] = [];</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">this</span>.handlers[type].push(handler);</div><div class="line">    &#125;,</div><div class="line">    fire: <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</div><div class="line">        <span class="keyword">if</span> (!event.target) &#123;</div><div class="line">            event.target = <span class="keyword">this</span>;</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.handlers[event.type] <span class="keyword">instanceof</span> <span class="built_in">Array</span>) &#123;</div><div class="line">            <span class="keyword">var</span> handlers = <span class="keyword">this</span>.handlers[event.type];</div><div class="line">            <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, len = handlers.length; i &lt; len; i++) &#123;</div><div class="line">                handlers[i](event);</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;,</div><div class="line">    removeHandler: <span class="function"><span class="keyword">function</span>(<span class="params">type, handler</span>) </span>&#123;</div><div class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.handlers[type] <span class="keyword">instanceof</span> <span class="built_in">Array</span>) &#123;</div><div class="line">            <span class="keyword">var</span> handlers = <span class="keyword">this</span>.handlers[type];</div><div class="line">            <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, len = handlers.length; i &lt; len; i++) &#123;</div><div class="line">                <span class="keyword">if</span> (handlers[i] === handler) &#123;</div><div class="line">                    <span class="keyword">break</span>;</div><div class="line">                &#125;</div><div class="line">            &#125;</div><div class="line">            handlers.splice(i, <span class="number">1</span>);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>EventTarget 类型有一个单独的属性handlers，用于储存事件处理程序。<br>还有三个方法：addHandler() ， 用于注册给定类型事件的事件处理程序；<br>fire() ， 用于触发一个事件；<br>removeHandler()，用于注销某个事件类型的事件处理程序。</p>
<p>addHandler()方法接受两个参数：事件类型和用于处理该事件的函数。<br>当调用该方法时，会进行一次检查，看看handlers 属性中是否已经存在一个针对该事件类型的数组；<br>如果没有，则创建一个新的。<br>然后使用push()将该处理程序添加到数组的末尾。</p>
<p>如果要触发一个事件，要调用fire()函数。<br>该方法接受一个单独的参数，是一个至少包含type属性的对象。<br>fire()方法先给event 对象设置一个target 属性，如果它尚未被指定的话。<br>然后它就查找对应该事件类型的一组处理程序，调用各个函数，并给出event 对象。<br>因为这些都是自定义事件，所以event 对象上还需要的额外信息由你自己决定。</p>
<p>removeHandler()方法是addHandler()的辅助，它们接受的参数一样：事件的类型和事件处理程序。<br>这个方法搜索事件处理程序的数组找到要删除的处理程序的位置。如果找到了，则使用break操作符退出for 循环。<br>然后使用splice()方法将该项目从数组中删除。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">handleMessage</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">alert(<span class="string">"Message received: "</span> + event.message);</div><div class="line">&#125;</div><div class="line"><span class="comment">//创建一个新对象</span></div><div class="line"><span class="keyword">var</span> target = <span class="keyword">new</span> EventTarget();</div><div class="line"><span class="comment">//添加一个事件处理程序</span></div><div class="line">target.addHandler(<span class="string">"message"</span>, handleMessage);</div><div class="line"><span class="comment">//触发事件</span></div><div class="line">target.fire(&#123; type: <span class="string">"message"</span>, message: <span class="string">"Hello world!"</span>&#125;);</div><div class="line"><span class="comment">//删除事件处理程序</span></div><div class="line">target.removeHandler(<span class="string">"message"</span>, handleMessage);</div><div class="line"><span class="comment">//再次，应没有处理程序</span></div><div class="line">target.fire(&#123; type: <span class="string">"message"</span>, message: <span class="string">"Hello world!"</span>&#125;);</div></pre></td></tr></table></figure>
<p>因为这种功能是封装在一种自定义类型中的，其他对象可以继承EventTarget 并获得这个行为。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">name, age</span>)</span>&#123;</div><div class="line">    EventTarget.call(<span class="keyword">this</span>);</div><div class="line">    <span class="keyword">this</span>.name = name;</div><div class="line">    <span class="keyword">this</span>.age = age;</div><div class="line">&#125;</div><div class="line">inheritPrototype(Person,EventTarget);</div><div class="line">Person.prototype.say = <span class="function"><span class="keyword">function</span>(<span class="params">message</span>)</span>&#123;</div><div class="line">    <span class="keyword">this</span>.fire(&#123;type: <span class="string">"message"</span>, message: message&#125;);</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>Person 类型使用了寄生组合继承方法来继承EventTarget。<br>一旦调用了say()方法，便触发了事件，它包含了消息的细节。<br>在某种类型的另外的方法中调用fire()方法是很常见的，同时它通常不是公开调用的。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">handleMessage</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">alert(event.target.name + <span class="string">" says: "</span> + event.message);</div><div class="line">&#125;</div><div class="line"><span class="comment">//创建新person</span></div><div class="line"><span class="keyword">var</span> person = <span class="keyword">new</span> Person(<span class="string">"Nicholas"</span>, <span class="number">29</span>);</div><div class="line"><span class="comment">//添加一个事件处理程序</span></div><div class="line">person.addHandler(<span class="string">"message"</span>, handleMessage);</div><div class="line"><span class="comment">//在该对象上调用1 个方法，它触发消息事件</span></div><div class="line">person.say(<span class="string">"Hi there."</span>);</div></pre></td></tr></table></figure>
<p>当代码中存在多个部分在特定时刻相互交互的情况下，自定义事件就非常有用了。<br>这时，如果每个对象都有对其他所有对象的引用，那么整个代码就会紧密耦合，同时维护也变得很困难，因为对某个对象的修改也会影响到其他对象。<br>使用自定义事件有助于解耦相关对象，保持功能的隔绝。<br>在很多情况中，触发事件的代码和监听事件的代码是完全分离的。</p>
<h2 id="拖放"><a href="#拖放" class="headerlink" title="拖放"></a>拖放</h2><p>拖放是一种非常流行的用户界面模式。它的概念很简单：点击某个对象，并按住鼠标按钮不放，将鼠标移动到另一个区域，然后释放鼠标按钮将对象“放”在这里。<br>拖放功能也流行到了Web 上，成为了一些更传统的配置界面的一种候选方案。</p>
<p>拖放的基本概念很简单：创建一个绝对定位的元素，使其可以用鼠标移动。这个技术源自一种叫做“鼠标拖尾”的经典网页技巧。<br>鼠标拖尾是一个或者多个图片在页面上跟着鼠标指针移动。</p>
<p>单元素鼠标拖尾的基本代码需要为文档设置一个onmousemove 事件处理程序，它总是将指定元素移动到鼠标指针的位置。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">EventUtil.addHandler(<span class="built_in">document</span>, <span class="string">"mousemove"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line"><span class="keyword">var</span> myDiv = <span class="built_in">document</span>.getElementById(<span class="string">"myDiv"</span>);</div><div class="line">myDiv.style.left = event.clientX + <span class="string">"px"</span>;</div><div class="line">myDiv.style.top = event.clientY + <span class="string">"px"</span>;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>在这个例子中，元素的left 和top 坐标设置为了event 对象的clientX 和clientY 属性，这就将元素放到了视口中指针的位置上。<br>它的效果是一个元素始终跟随指针在页面上的移动。</p>
<p>只要正确的时刻（当鼠标按钮按下的时候）实现该功能，并在之后删除它（当释放鼠标按钮时），就可以实现拖放了。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> DragDrop = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line"><span class="keyword">var</span> dragging = <span class="literal">null</span>;</div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">handleEvent</span>(<span class="params">event</span>)</span>&#123;</div><div class="line"><span class="comment">//获取事件和目标</span></div><div class="line">event = EventUtil.getEvent(event);</div><div class="line"><span class="keyword">var</span> target = EventUtil.getTarget(event);</div><div class="line"><span class="comment">//确定事件类型</span></div><div class="line"><span class="keyword">switch</span>(event.type)&#123;</div><div class="line"><span class="keyword">case</span> <span class="string">"mousedown"</span>:</div><div class="line"><span class="keyword">if</span> (target.className.indexOf(<span class="string">"draggable"</span>) &gt; <span class="number">-1</span>)&#123;</div><div class="line">dragging = target;</div><div class="line">&#125;</div><div class="line"><span class="keyword">break</span>;</div><div class="line"><span class="keyword">case</span> <span class="string">"mousemove"</span>:</div><div class="line"><span class="keyword">if</span> (dragging !== <span class="literal">null</span>)&#123;</div><div class="line"><span class="comment">//指定位置</span></div><div class="line">dragging.style.left = event.clientX + <span class="string">"px"</span>;</div><div class="line">dragging.style.top = event.clientY + <span class="string">"px"</span>;</div><div class="line">&#125;</div><div class="line"><span class="keyword">break</span>;</div><div class="line"><span class="keyword">case</span> <span class="string">"mouseup"</span>:</div><div class="line">dragging = <span class="literal">null</span>;</div><div class="line"><span class="keyword">break</span>;</div><div class="line">&#125;</div><div class="line">&#125;;</div><div class="line"><span class="comment">//公共接口</span></div><div class="line"><span class="keyword">return</span> &#123;</div><div class="line">enable: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">EventUtil.addHandler(<span class="built_in">document</span>, <span class="string">"mousedown"</span>, handleEvent);</div><div class="line">EventUtil.addHandler(<span class="built_in">document</span>, <span class="string">"mousemove"</span>, handleEvent);</div><div class="line">EventUtil.addHandler(<span class="built_in">document</span>, <span class="string">"mouseup"</span>, handleEvent);</div><div class="line">&#125;,</div><div class="line">disable: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">EventUtil.removeHandler(<span class="built_in">document</span>, <span class="string">"mousedown"</span>, handleEvent);</div><div class="line">EventUtil.removeHandler(<span class="built_in">document</span>, <span class="string">"mousemove"</span>, handleEvent);</div><div class="line">EventUtil.removeHandler(<span class="built_in">document</span>, <span class="string">"mouseup"</span>, handleEvent);</div><div class="line">&#125;</div><div class="line">&#125;</div><div class="line">&#125;();</div></pre></td></tr></table></figure>
<p>DragDrop 对象封装了拖放的所有基本功能。这是一个单例对象，并使用了模块模式来隐藏某些实现细节。<br>dragging 变量起初是null，将会存放被拖动的元素，所以当该变量不为null 时，就知道正在拖动某个东西。</p>
<p>handleEvent()函数处理拖放功能中的所有的三个鼠标事件。<br>它首先获取event 对象和事件目标的引用。<br>之后，用一个switch 语句确定要触发哪个事件样式。<br>当mousedown 事件发生时，会检查target 的class 是否包含”draggable”类，如果是，那么将target 存放到dragging中。<br>这个技巧可以很方便地通过标记语言而非JavaScript 脚本来确定可拖动的元素。</p>
<p>handleEvent()的mousemove 情况和前面的代码一样，不过要检查dragging 是否为null。<br>当它不是null，就知道dragging 就是要拖动的元素，这样就会把它放到恰当的位置上。</p>
<p>mouseup 情况就仅仅是将dragging 重置为null，让mousemove 事件中的判断失效。</p>
<p>DragDrop 还有两个公共方法：enable()和disable()，它们只是相应添加和删除所有的事件处理程序。<br>这两个函数提供了额外的对拖放功能的控制手段。</p>
<p>要使用DragDrop 对象，只要在页面上包含这些代码并调用enable()。拖放会自动针对所有包含”draggable”类的元素启用。<br><code>&lt;div class=&quot;draggable&quot; style=&quot;position:absolute; background:red&quot;&gt; &lt;/div&gt;</code><br>注意为了元素能被拖放，它必须是绝对定位的。</p>
<h3 id="修缮拖动功能"><a href="#修缮拖动功能" class="headerlink" title="修缮拖动功能"></a>修缮拖动功能</h3><p>试了上面的例子之后会发现元素的左上角总是和指针在一起。<br>这个结果对用户来说有一点不爽，因为当鼠标开始移动的时候，元素好像是突然跳了一下。<br>理想情况是，这个动作应该看上去好像这个元素是被指针“拾起”的，也就是说当在拖动元素的时候，用户点击的那一点就是指针应该保持的位置。</p>
<p>要达到需要的效果，必须做一些额外的计算。需要计算元素左上角和指针位置之间的差值。<br>这个差值应该在mousedown 事件发生的时候确定，并且一直保持，直到mouseup 事件发生。<br>通过将event的clientX 和clientY 属性与该元素的offsetLeft 和offsetTop 属性进行比较，就可以算出水平方向和垂直方向上需要多少空间。</p>
<p>为了保存x 和y 坐标上的差值，还需要几个变量。diffX 和diffY 这些变量需要在onmousemove事件处理程序中用到，来对元素进行适当的定位。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line">...</div><div class="line">var dragging = <span class="literal">null</span>;</div><div class="line">diffX = <span class="number">0</span>;</div><div class="line">diffY = <span class="number">0</span>;</div><div class="line">...</div><div class="line">case <span class="string">"mousedown"</span>:</div><div class="line"><span class="keyword">if</span> (target.className.indexOf(<span class="string">"draggable"</span>) &gt; <span class="number">-1</span>)&#123;</div><div class="line">dragging = target;</div><div class="line">diffX = event.clientX - target.offsetLeft;</div><div class="line">diffY = event.clientY - target.offsetTop;</div><div class="line">&#125;</div><div class="line"><span class="keyword">break</span>;</div><div class="line"><span class="keyword">case</span> <span class="string">"mousemove"</span>:</div><div class="line"><span class="keyword">if</span> (dragging !== <span class="literal">null</span>)&#123;</div><div class="line"><span class="comment">//指定位置</span></div><div class="line">dragging.style.left = (event.clientX - diffX) + <span class="string">"px"</span>;</div><div class="line">dragging.style.top = (event.clientY - diffY) + <span class="string">"px"</span>;</div><div class="line">&#125;</div><div class="line"><span class="keyword">break</span>;</div><div class="line">...</div></pre></td></tr></table></figure>
<p>diffX 和diffY 变量是私有的，因为只有handleEvent()函数需要用到它们。<br>当mousedown 事件发生时，通过clientX 减去目标的offsetLeft，clientY 减去目标的offsetTop，可以计算到这两个变量的值。<br>当触发了mousemove 事件后，就可以使用这些变量从指针坐标中减去，得到最终的坐标。<br>最后得到一个更加平滑的拖动体验，更加符合用户所期望的方式。</p>
<h3 id="添加自定义事件"><a href="#添加自定义事件" class="headerlink" title="添加自定义事件"></a>添加自定义事件</h3><p>拖放功能还不能真正应用起来，除非能知道什么时候拖动开始了。<br>从这点上看，前面的代码没有提供任何方法表示拖动开始、正在拖动或者已经结束。<br>这时，可以使用自定义事件来指示这几个事件的发生，让应用的其他部分与拖动功能进行交互。<br>由于DragDrop 对象是一个使用了模块模式的单例，所以需要进行一些更改来使用EventTarget类型。</p>
<p>首先，创建一个新的EventTarget 对象，然后添加enable()和disable()方法，最后返回这个对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> DragDrop = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line"><span class="keyword">var</span> dragdrop = <span class="keyword">new</span> EventTarget(),</div><div class="line">dragging = <span class="literal">null</span>,</div><div class="line">diffX = <span class="number">0</span>,</div><div class="line">diffY = <span class="number">0</span>;</div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">handleEvent</span>(<span class="params">event</span>)</span>&#123;</div><div class="line"><span class="comment">//获取事件和对象</span></div><div class="line">event = EventUtil.getEvent(event);</div><div class="line"><span class="keyword">var</span> target = EventUtil.getTarget(event);</div><div class="line"><span class="comment">//确定事件类型</span></div><div class="line"><span class="keyword">switch</span>(event.type)&#123;</div><div class="line"><span class="keyword">case</span> <span class="string">"mousedown"</span>:</div><div class="line"><span class="keyword">if</span> (target.className.indexOf(<span class="string">"draggable"</span>) &gt; <span class="number">-1</span>)&#123;</div><div class="line">dragging = target;</div><div class="line">diffX = event.clientX - target.offsetLeft;</div><div class="line">diffY = event.clientY - target.offsetTop;</div><div class="line">dragdrop.fire(&#123;type:<span class="string">"dragstart"</span>, target: dragging,</div><div class="line">x: event.clientX, y: event.clientY&#125;);</div><div class="line">&#125;</div><div class="line"><span class="keyword">break</span>;</div><div class="line"><span class="keyword">case</span> <span class="string">"mousemove"</span>:</div><div class="line"><span class="keyword">if</span> (dragging !== <span class="literal">null</span>)&#123;</div><div class="line"><span class="comment">//指定位置</span></div><div class="line">dragging.style.left = (event.clientX - diffX) + <span class="string">"px"</span>;</div><div class="line">dragging.style.top = (event.clientY - diffY) + <span class="string">"px"</span>;</div><div class="line"><span class="comment">//触发自定义事件</span></div><div class="line">dragdrop.fire(&#123;type:<span class="string">"drag"</span>, target: dragging,</div><div class="line">x: event.clientX, y: event.clientY&#125;);</div><div class="line">&#125;</div><div class="line"><span class="keyword">break</span>;</div><div class="line"><span class="keyword">case</span> <span class="string">"mouseup"</span>:</div><div class="line">dragdrop.fire(&#123;type:<span class="string">"dragend"</span>, target: dragging,</div><div class="line">x: event.clientX, y: event.clientY&#125;);</div><div class="line">dragging = <span class="literal">null</span>;</div><div class="line"><span class="keyword">break</span>;</div><div class="line">&#125;</div><div class="line">&#125;;</div><div class="line"><span class="comment">//公共接口</span></div><div class="line">dragdrop.enable = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">EventUtil.addHandler(<span class="built_in">document</span>, <span class="string">"mousedown"</span>, handleEvent);</div><div class="line">EventUtil.addHandler(<span class="built_in">document</span>, <span class="string">"mousemove"</span>, handleEvent);</div><div class="line">EventUtil.addHandler(<span class="built_in">document</span>, <span class="string">"mouseup"</span>, handleEvent);</div><div class="line">&#125;;</div><div class="line">dragdrop.disable = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">EventUtil.removeHandler(<span class="built_in">document</span>, <span class="string">"mousedown"</span>, handleEvent);</div><div class="line">EventUtil.removeHandler(<span class="built_in">document</span>, <span class="string">"mousemove"</span>, handleEvent);</div><div class="line">EventUtil.removeHandler(<span class="built_in">document</span>, <span class="string">"mouseup"</span>, handleEvent);</div><div class="line">&#125;;</div><div class="line"><span class="keyword">return</span> dragdrop;</div><div class="line">&#125;();</div></pre></td></tr></table></figure>
<p>这段代码定义了三个事件：dragstart、drag 和dragend。它们都将被拖动的元素设置为了target，并给出了x 和y 属性来表示当前的位置。<br>它们触发于dragdrop 对象上，之后在返回对象前给对象增加enable()和disable()方法。<br>这些模块模式中的细小更改令DragDrop 对象支持了事件。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">DragDrop.addHandler(<span class="string">"dragstart"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line"><span class="keyword">var</span> status = <span class="built_in">document</span>.getElementById(<span class="string">"status"</span>);</div><div class="line">status.innerHTML = <span class="string">"Started dragging "</span> + event.target.id;</div><div class="line">&#125;);</div><div class="line">DragDrop.addHandler(<span class="string">"drag"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line"><span class="keyword">var</span> status = <span class="built_in">document</span>.getElementById(<span class="string">"status"</span>);</div><div class="line">status.innerHTML += <span class="string">"&lt;br/&gt; Dragged "</span> + event.target.id + <span class="string">" to ("</span> + event.x +</div><div class="line"><span class="string">","</span> + event.y + <span class="string">")"</span>;</div><div class="line">&#125;);</div><div class="line">DragDrop.addHandler(<span class="string">"dragend"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line"><span class="keyword">var</span> status = <span class="built_in">document</span>.getElementById(<span class="string">"status"</span>);</div><div class="line">status.innerHTML += <span class="string">"&lt;br/&gt; Dropped "</span> + event.target.id + <span class="string">" at ("</span> + event.x +</div><div class="line"><span class="string">","</span> + event.y + <span class="string">")"</span>;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>这里，为DragDrop 对象的每个事件添加了事件处理程序。还使用了一个元素来实现被拖动的元素当前的状态和位置。<br>一旦元素被放下了，就可以看到从它一开始被拖动之后经过的所有的中间步骤。<br>为DragDrop 添加自定义事件可以使这个对象更健壮，它将可以在网络应用中处理复杂的拖放功能。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Web/" rel="tag"># Web</a>
          
            <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/11/07/javascript-note-22-2/" rel="next" title="《 JavaScript 高级程序设计》备忘-第二十二章-2">
                <i class="fa fa-chevron-left"></i> 《 JavaScript 高级程序设计》备忘-第二十二章-2
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/11/08/javascript-note-23-1/" rel="prev" title="《 JavaScript 高级程序设计》备忘-第二十三章-1">
                《 JavaScript 高级程序设计》备忘-第二十三章-1 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="Huang SJ" />
          <p class="site-author-name" itemprop="name">Huang SJ</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">75</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hsj1992" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/hsj9527" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/1694147905" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.freecodecamp.cn/hsj1992" target="_blank" title="FreeCodeCamp">
                  
                    <i class="fa fa-fw fa-fire"></i>
                  
                  FreeCodeCamp
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://codepen.io/hsj1992/" target="_blank" title="codepen">
                  
                    <i class="fa fa-fw fa-codepen"></i>
                  
                  codepen
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://hsj1992.oschina.io/" target="_blank" title="码云镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  码云镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://hsj1992.coding.me/" target="_blank" title="coding镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  coding镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://hsj1992.github.io/" target="_blank" title="github镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  github镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://codingme-6dd8a.firebaseapp.com" target="_blank" title="Firebase镜像">
                  
                    <i class="fa fa-fw fa-google"></i>
                  
                  Firebase镜像
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#高级技巧"><span class="nav-number">1.</span> <span class="nav-text">高级技巧</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#自定义事件"><span class="nav-number">1.1.</span> <span class="nav-text">自定义事件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#拖放"><span class="nav-number">1.2.</span> <span class="nav-text">拖放</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#修缮拖动功能"><span class="nav-number">1.2.1.</span> <span class="nav-text">修缮拖动功能</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#添加自定义事件"><span class="nav-number">1.2.2.</span> <span class="nav-text">添加自定义事件</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Huang SJ</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="//cdn.staticfile.org/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/jquery_lazyload/1.9.7/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/velocity/1.2.1/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/velocity/1.2.1/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


</body>
</html>
